<?php

namespace GordenSong\Support;


use GordenSong\Utils\RuleUtil;
use GordenSong\Utils\SceneUtil;

trait SceneTrait
{
	protected $scenes = [];

	/**
	 * 获取指定场景名称的字段列表及扩展规则
	 * @param string $name
	 * @return array
	 */
	public function getScene(string $name): array
	{
		return data_get($this->scenes, $name, []);
	}

	protected function normalizeScenes(): void
	{
		$scenes = $this->scenes;
		foreach ($scenes as $name => $sceneValues) {
			$this->addScene($name, $sceneValues);
		}
	}

	/**
	 * 添加指定名称的场景
	 * @param string $name
	 * @param array $fields
	 */
	public function addScene(string $name, array $fields)
	{
		$this->scenes[$name] = SceneUtil::normalize($fields);
	}

	public function setScenes(array $scenes)
	{
		$this->scenes = $scenes;
		$this->normalizeScenes();
		return $this;
	}

	/**
	 * @return array
	 */
	public function getScenes(): array
	{
		return $this->scenes;
	}

	/**
	 * 获取多场景规则并集
	 * @param string ...$scenes
	 */
	public function scene(string ...$scenes)
	{
		$sceneRules = [];
		foreach ($scenes as $scene) {
			$sceneRules = RuleUtil::mergeManyRules($sceneRules, $this->getScene($scene));
		}
		$sceneFields = array_keys($sceneRules);

		$rules = [];

		foreach ($sceneFields as $field) {
			$rules[$field] = array_values(RuleUtil::mergeRules(data_get($this->rules(), $field, []), $sceneRules[$field]));
		}
		$this->rules = RuleUtil::mergeManyRules([], $rules);

		return $this;
	}
}
